package com.listen.service.DB;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.listen.common.DateFormatUtil;
import com.listen.common.HttpClientProxy;
import com.listen.common.HttpClientUtil;
import com.listen.common.IPProxyNew;
import com.listen.common.Img2Base64Util;
import com.listen.common.SanLeiConfigUtils;
import com.listen.common.SpecialCharacterHandler;
import com.listen.model.User;
import com.listen.vo.ClassParmsVO;
import com.listen.vo.HeadParmsVO;
/**
 * 三类延期听课
 */
public class AnguanContinueServiceImplDB{
	private static final Logger log = LoggerFactory.getLogger(AnguanContinueServiceImplDB.class);
	private ConcurrentHashMap<String, Object>  resultMap = null;
	private HttpClientProxy instance = new HttpClientProxy();
	private CloseableHttpResponse response = null;
	private CloseableHttpClient httpClient = null;
	private Map<String,Object> answerMap = null;
	private String proxyInfo = null;
	private int flag;
	//private String cookie = "";
	//private String checkUid = "";
	private String baseCookie = "";
	private String uid = "";
	private String paramid = "";
	private String __EVENTTARGET = "";
	private String __EVENTARGUMENT = "";
	private String __VIEWSTATE = "";
	private String __VIEWSTATEGENERATOR = "";
	
	public static void main(String args[]) throws InterruptedException{
		IPProxyNew proxy = new IPProxyNew(null);
		AnguanContinueServiceImplDB yanqi = new AnguanContinueServiceImplDB();
		User user = new User();
		String code = "362323197201210212";
		String[] codes = code.split(",");
		user.setZy("B2");
		user.setZyName("新三类继续教育");
		user.setAddress("http://urdt.cn:8055");
		user.setCreateTm(DateFormatUtil.getDateByStr("20191231"));
		user.setAllNum(20);
		user.setStatus(2);
		user.setPassword("888888");
		String ip = proxy.getOneIpAndPort();
		for(int k = 0;k < codes.length;k++) {
			user.setCode(codes[k]);
			for(int i=1;i<=20;i++) {
				user.setNowNum(i);
				yanqi.listen(user,ip);
				Thread.sleep(1000);
			}
		}
		
	}
	
	//听课业务
	public Map<String,Object> listen(User user,String ip){
		this.proxyInfo = ip;
		//System.out.println("proxyInfo="+proxyInfo);
		ClassParmsVO vo = new ClassParmsVO();
		resultMap = new ConcurrentHashMap<>();
		resultMap.put("successFlag", "0");
		resultMap.put("dayNum", "0");
		resultMap.put("addNum", "0");
		if(user.getStatus()==1)
			this.flag = 1;
		//状态为2已听完课，flag=3直接考试
		if(user.getStatus()==2)
			this.flag = 3;
		try {
			resolverHtml(vo,user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	//跳转到具体专业登录页面,并抓取登錄參數
	private void resolverHtml(ClassParmsVO vo,User user){
		String url = user.getAddress();
		response = instance.sendHttpGet(httpClient, url, proxyInfo);
		HttpEntity entity = response.getEntity();  
		try {
			String html = EntityUtils.toString(entity, "UTF-8");
			Document document = Jsoup.parse(html);
		    Element parm1 = document.getElementById("__EVENTVALIDATION");
		    vo.set__eventvalidation(parm1.attr("value"));
		    Element parm2 = document.getElementById("__VIEWSTATE");
		    vo.set__viewstate(parm2.attr("value"));
		    login(vo,user);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//登录
	private void login(ClassParmsVO vo,User user){
		String code= user.getCode();
		String loginUrl = user.getAddress() + "/Login.aspx";
		Map<String, String> maps = new HashMap<String, String>();
		maps.put("__VIEWSTATE", vo.get__viewstate()); 
        maps.put("__EVENTVALIDATION",vo.get__eventvalidation());
        maps.put("txtUserName",code); 
        maps.put("txtPwd",user.getPassword());
        maps.put("ddlType", "2");//学员登录 
        maps.put("btnLogin", "");
        maps.put("txtLoginName", ""); 
        maps.put("txtDM", "");
        maps.put("txtFR", ""); 
        maps.put("zhjg", "");
        maps.put("zhfr", "");
        try {
        	HeadParmsVO head = new HeadParmsVO();
	        head.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			head.setContentType("application/x-www-form-urlencoded");
			response = instance.sendHttpPost(httpClient, head, loginUrl, maps, proxyInfo);
        	int state = response.getStatusLine().getStatusCode();
        	vo.setLoginState(state);
        	if(state==302 || state==200){
        		Thread.sleep(1000);
        		Header[] hearders = response.getHeaders("Set-Cookie");
        		
        		String sessionIdCookie = hearders[0].getValue();
        		String sessionId = sessionIdCookie.substring(0, sessionIdCookie.indexOf(";") + 1);
        		vo.setSessionId(sessionId);
        		
        		String userIdCookie = hearders[1].getValue();
        		String userid = userIdCookie.substring(0, userIdCookie.indexOf(";") + 1);
        		vo.setUserid(userid);
        		
        		String infoCookies = hearders[2].getValue();
        		String info = infoCookies.substring(0, infoCookies.indexOf(";") + 1);
        		vo.setInfo(info);
        		
        		this.uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
        		this.baseCookie = sessionId + userid + info;
        		if(flag==3){//只考试
        			testPaper(vo,user);
        		}else if(flag==2 || flag == 1){
        			shipinSection(vo,user);
        			//webForm(vo,user);//听课，考试
        		}else{
        			print(user.getZyName()+"-"+user.getCode()+"-登录成功后跳转标识异常-flag="+flag);
        			logout(vo,user);
        		}
        	}else{
        		print(user.getZyName()+"-"+user.getCode()+"-登录失败--->"+state);
        		logout(vo,user);
        	}
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-登录异常--->"+e);
			logout(vo,user);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	//点击视频教程
	public void shipinSection(ClassParmsVO vo,User user) {
		String zyName = user.getZyName();
		int i = user.getNowNum();
		String shipinSection_url = user.getAddress() + "/ShiPinJiaoCheng/shipinSection.aspx";
		user.setReferer(shipinSection_url);
		String cookie = this.baseCookie;
		HeadParmsVO heads = new HeadParmsVO();
		heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
		heads.setCookie(cookie);
		heads.setUpgradeInsecureRequests("1");
		try {
			response = instance.sendHttpGet(httpClient,heads, shipinSection_url,proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			//Thread.sleep(1000);
			if(state == 200){
				//print(zyName+"-"+ user.getCode() +" 第"+i +"个视频,shipinSection-->方法请求成功:"+state);
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity);
				Document document = Jsoup.parse(html);
				
				Element parm3 = document.getElementById("__VIEWSTATE");
				this.__VIEWSTATE = parm3.attr("value");
				
				Element parm4 = document.getElementById("__VIEWSTATEGENERATOR");
				this.__VIEWSTATEGENERATOR = parm4.attr("value");
				isStudy(vo,user);
			}else{
				print(zyName+"-"+ user.getCode() +" 第"+i +"个视频,shipinSection-->方法请求失败:"+state);
			}
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-shipinSection-->方法请求异常:"+e);
			logout(vo,user);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
		
	}
	//开始学习
	private void isStudy(ClassParmsVO vo,User user) {
		int i = user.getNowNum();
		int end = i%10;
		String id = "";
		if(i < 10) {
			id = "1000"+end;
		}else if(i >=10 && i <14){
			id = "1030"+(end+1);
		}else if(i >=14 && i <18){
			id = "1040"+(end-3);
		}else{
			id = "1050"+((i+3)%10);
		}
		this.paramid = id;
		String isStudy_url = user.getAddress() + "/myclass/IsStudy.aspx?id="+paramid;
		//System.out.println(isStudy_url);
		HeadParmsVO heads = new HeadParmsVO();
		heads.setCookie(this.baseCookie);
		heads.setReferer(user.getReferer());
		user.setReferer(isStudy_url);//设置referer
		try {
			Thread.sleep(1000);
			response = instance.sendHttpGet(httpClient,heads, isStudy_url,proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
			//System.out.println(resMsg);
			if(state == 200){
				//print(user.getZyName()+"-"+ user.getCode() +" 第"+i +"个视频,-isStudy-->请求成功:"+state);
				shipinSectionPost(vo,user);
			}else{
				print(user.getZyName()+"-"+ user.getCode() +" 第"+i +"个视频,-isStudy-->请求失败:"+state);
			}
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-isStudy-->请求异常:"+e);
			logout(vo,user);
		}finally {
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	public void shipinSectionPost(ClassParmsVO vo,User user) {
		String shipinSectionPost_url = user.getAddress() + "/ShiPinJiaoCheng/shipinSection.aspx";
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setContentType("application/x-www-form-urlencoded");
	    heads.setxRequestedWith("XMLHttpRequest");
	    heads.setCookie(this.baseCookie);
    	heads.setReferer(user.getReferer());
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	int nowNum = user.getNowNum();
    	Map<String, String> maps = new HashMap<String, String>();
    	maps.put("__EVENTTARGET", this.__EVENTTARGET);
		maps.put("__EVENTARGUMENT", this.__EVENTARGUMENT);
        maps.put("__VIEWSTATE", this.__VIEWSTATE); 
        maps.put("__VIEWSTATEGENERATOR",this.__VIEWSTATEGENERATOR);
        maps.put("dr1","103");
        int k = (nowNum-1)%10;
        String key = "rep1:ctl"+ k +"Button1";
        maps.put(key, "进入听课");
        
        user.setReferer(shipinSectionPost_url);
        try {
        	Thread.sleep(1000);
        	response = instance.sendHttpPost(httpClient, heads, shipinSectionPost_url, maps, proxyInfo);
        	int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
    			//print(user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection-post--> 请求成功"+status);
    			watchVideo(vo,user);
    		}else {
    			print(user.getZyName()+"-"+user.getCode() +"-第"+nowNum+"个视频-shipinSection-post--> 请求成功"+status);
    		}
		} catch (Exception e) {
			print(user.getZyName()+"-"+user.getCode() +"-第"+ nowNum +"个视频-shipinSection-post--> 请求异常"+e);
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	public void watchVideo(ClassParmsVO vo,User user){
		int nowNum = user.getNowNum();
		String watchVideo_url = user.getAddress() +"/myclass/WatchVideo.aspx?id="+this.paramid;
		HeadParmsVO heads = new HeadParmsVO();
	    heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
	    heads.setAcceptEncoding("gzip, deflate");
	    heads.setAcceptLanguage("zh-CN,zh;q=0.9");
	    heads.setCookie(this.baseCookie);
    	heads.setReferer(user.getReferer());
    	heads.setUpgradeInsecureRequests("1");
    	heads.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.117 Safari/537.36");
    	try {
    		Thread.sleep(1000);
    		response = instance.sendHttpGet(httpClient, heads, watchVideo_url, proxyInfo);
    		int status = response.getStatusLine().getStatusCode();
    		if(status == 200) {
				user.setReferer(watchVideo_url);
				//print(user.getZyName()+"-"+user.getCode() +"-第"+ nowNum +"个视频-watchVideo--> 请求成功"+status);
				webForm(vo,user);
    		}else {
    			print(user.getZyName()+"-"+user.getCode() +"-第"+ nowNum +"个视频-watchVideo--> 请求失败"+status);
    		}
		} catch (Exception e) {
			print(user.getZyName()+"-"+user.getCode() +"-第"+ nowNum +"个视频-watchVideo--> 请求一次"+e);
		}finally {
			instance.closeResource(response, httpClient);
		}
	}
	
	//人脸验证
	private void webForm(ClassParmsVO vo,User user){
		Map<String, String> maps = new HashMap<String, String>();
		String os = System.getProperty("os.name");
		String path = "";
		Date d = user.getCreateTm() == null ? new Date() : user.getCreateTm();
		String dataStr = DateFormatUtil.getDateStr(d, "yyyyMMdd");
		if(os.toLowerCase().startsWith("win")){  
			path = "D:\\photos\\"+dataStr+"\\";
		}else {
			path = "/home/listen/photos/"+dataStr+"/";
		}
		int i = user.getNowNum();
		String code = user.getCode();
		String zyName = user.getZyName();
		String webUrl = user.getAddress() + "/myclass/WebForm1.aspx";
        try {
        	Thread.sleep(4000);
        	String image = "data:image/png;base64,"+Img2Base64Util.getImgStr(path + code +".png");
			//System.out.println(image);
			String referer = user.getReferer();
			String url = SpecialCharacterHandler.replaceAll(referer);
			maps.put("type", "data"); 
	        maps.put("image",image);
        	//st构建
			String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
			st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
			String cookies = this.baseCookie + "totaltime=2326; url="+url+"; checkUid="+uid+"; st="+ st +";nowtime=27";
			//System.out.println(cookies);
			HeadParmsVO heads = new HeadParmsVO();
			heads.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setxRequestedWith("XMLHttpRequest");
			heads.setCookie(cookies);
			response = instance.sendHttpPost(httpClient, heads, webUrl, maps, proxyInfo);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 200){
        		String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
				print(zyName+"-"+ code +" 第"+i +"个视频"+resMsg);
				updateClassState(vo,user);
			}else{
				String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
				print(zyName+"-"+ code +" 第"+i +"个视频人脸识别失败"+resMsg);
			}
        	
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-个视频人脸识别异常--->"+e);
			logout(vo,user);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	//修改课件状态
	private void updateClassState(ClassParmsVO vo,User user){
 		String code = user.getCode();
		String zyName = user.getZyName();
		int i = user.getNowNum();
		int classid = 0;
		if(i==1) {
			classid=220;
		}if(i>=2 && i<=7){
			classid=210+i;
		}if(i==8 || i==9){
			classid = 216+i;
		}if(i>=10 && i<=13){
			classid = 131 + i;
		}if(i>=14 && i<=17){
			classid = 134 + i;
		}if(i >=18 && i<=19){
			classid = 137+i;
		}if(i == 20)
			classid = 226;
		try {
			Thread.sleep(1000);
			//st构建
			String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(40);
			st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
			String cookie = this.baseCookie +"totaltime=2981;checkUid="+uid+";nowtime=2881;st="+st;
			String allUrl = user.getAddress() + "/EntpClass/Xtyl.ashx?classid="+ classid +"&uid="+uid;
			HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("*/*");
			heads.setxRequestedWith("XMLHttpRequest");
			heads.setContentType("application/json;utf-8");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setCookie(cookie);
			response = instance.sendHttpGet(httpClient, heads, allUrl, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				print(zyName+"-"+ code +" 第"+i +"个视频成功播放完!");
				resultMap.put("successFlag", "1");
				resultMap.put("dayNum", "1");
				resultMap.put("addNum", "1");
				if(user.getAllNum()==i)
					user.setStatus(2);
			}else{
				print(zyName+"-"+ code +" 第"+i +"个视频播放失败!state="+state);
			}
		} catch (Exception e) {
			printError(zyName+"-"+ code +" 第"+i +"个视频"+e);
		}finally{
			instance.closeResource(response, httpClient);
			HttpClientUtil.getInstance().closeResource(response);
			if(flag==2)//听课并考试
				submitPaper(vo,user);
			else//只听课，听完退出登录
				logout(vo,user);
		}
	}
		
	//人脸验证
	/*private void webForm(ClassParmsVO vo,User user){
		int i = user.getNowNum();
		String id = "";
		if(i < 10) {
			id = "1000" + i;
		}else {
			id = "100" + i;
		}
		String code = user.getCode();
		String zyName = user.getZyName();
		String webUrl = user.getAddress() + "/myclass/WebForm1.aspx";
		Map<String, String> maps = new HashMap<String, String>();
        try {
        	Thread.sleep(10000);
        	String image = PhotosConfigUtils.getConfig(code);
    		this.cookie = PhotosConfigUtils.getConfig(code+".cookie");
    		String referer = user.getAddress() + "/myclass/watchvideo.aspx?id="+id;
    		String url = SpecialCharacterHandler.replaceAll(referer);
    		maps.put("type", "data"); 
            maps.put("image",image);
        	//st构建
			String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(0);
			st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
			this.checkUid = this.cookie.split(";")[1].split("=")[1];
			String cookies = cookie+ "totaltime=2326; url="+url+"; checkUid="+checkUid+"; st="+ st +";nowtime=27";
			HeadParmsVO heads = new HeadParmsVO();
			heads.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setxRequestedWith("XMLHttpRequest");
			heads.setCookie(cookies);
			response = instance.sendHttpPost(httpClient, heads, webUrl, maps, proxyInfo);
        	int state = response.getStatusLine().getStatusCode();
        	if(state == 200){
        		String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
				print(zyName+"-"+ code +" 第"+i +"个视频 "+resMsg);
				updateClassState(vo,user);
			}else{
				print(zyName+"-"+ code +" 第"+i +"个视频播放失败!state="+state);
			}
		} catch (Exception e) {
			printError(user.getZyName()+"-"+user.getCode()+"-登录异常--->"+e);
			logout(vo,user);
		}finally{
			HttpClientUtil.getInstance().closeResource(response);
		}
	}
	
	private void updateClassState(ClassParmsVO vo,User user){
 		String code = user.getCode();
		String zyName = user.getZyName();
		int i = user.getNowNum();
		int classid = 0;
		if(i==1) {
			classid=220;
		}if(i>=2 && i<=7){
			classid=210+i;
		}if(i==8 || i==9){
			classid = 216+i;
		}if(i>=10 && i<=13){
			classid = 131 + i;
		}if(i>=14 && i<=17){
			classid = 134 + i;
		}if(i >=18 && i<=19){
			classid = 137+i;
		}if(i == 20)
			classid = 226;
		try {
			//st构建
			String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(40);
			st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
			String cookies = this.cookie + "totaltime=2981; checkUid="+checkUid+"; nowtime=2881; st="+st;
			String allUrl = user.getAddress() + "/EntpClass/Xtyl.ashx?classid="+ classid +"&uid="+checkUid;
			HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("application/json");
			heads.setxRequestedWith("XMLHttpRequest");
			heads.setContentType("application/json;utf-8");
			heads.setAcceptEncoding("gzip, deflate");
			heads.setCookie(cookies);
			response = instance.sendHttpGet(httpClient, heads, allUrl, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			if(state == 200){
				print(zyName+"-"+ code +" 第"+i +"个视频成功播放完!");
				resultMap.put("successFlag", "1");
				resultMap.put("dayNum", "1");
				resultMap.put("addNum", "1");
				if(user.getAllNum()==i)
					user.setStatus(2);
			}else{
				print(zyName+"-"+ code +" 第"+i +"个视频播放失败!state="+state);
			}
		} catch (Exception e) {
			printError(zyName+"-"+ code +" 第"+i +"个视频"+e);
		}finally{
			instance.closeResource(response, httpClient);
			HttpClientUtil.getInstance().closeResource(response);
			if(flag==2)//听课并考试
				submitPaper(vo,user);
			else//只听课，听完退出登录
				logout(vo,user);
		}
	}*/
	
	private void testPaper(ClassParmsVO vo,User user) {
		String testUrl = user.getAddress() + "/TR_TestPaper.aspx";
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		String userid = vo.getUserid();
		String cookie = sessionId + userid + info;
		HeadParmsVO heads = new HeadParmsVO();
		heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		heads.setCookie(cookie);
		response = instance.sendHttpGet(httpClient, heads, testUrl, proxyInfo);
		int state = response.getStatusLine().getStatusCode();
		try {
			Thread.sleep(2000);
			if(state == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				String html = EntityUtils.toString(entity, "UTF-8");
				Document document = Jsoup.parse(html);
				Element parm1 = document.getElementById("_thid");
				vo.setPid(parm1.attr("value"));
				Element parm2 = document.getElementById("Hidden1");
				vo.setQid(parm2.attr("value"));
				Element parm3 = document.getElementById("Hidden2");
				vo.setHid(parm3.attr("value"));
				/*System.out.println("pid="+vo.getPid());
				System.out.println("qid="+vo.getQid());
				System.out.println("hid="+vo.getHid());*/
				Thread.sleep(3*1000);
				submitPaper(vo,user);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	//提交试卷，考试
	private void submitPaper(ClassParmsVO vo,User user){
		//setParmsValue(vo,user);
		int i = user.getNowNum();
		String id = "";
		if(i < 10) {
			id = "1000" + i;
		}else {
			id = "100" + i;
		}
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		String code = user.getCode();
		String zyName = user.getZyName();
		try {
			String st = DateFormatUtil.getDateAnyMinuteBeforeFoer8(40);
			st = st.replaceAll(" ", "%20").replaceAll(":", "%3A");
			//设置答案
			String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String referer = user.getAddress() + "/TR_TestPaper.aspx?id="+id;
			String url = SpecialCharacterHandler.replaceAll(referer);
			String cookie = sessionId + userid + info +"totaltime=2881;url="+url+"; checkUid="+uid+";nowtime=2856;st="+st;
	        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();  
	        params.add(new BasicNameValuePair("Pid", vo.getPid()));  
	        params.add(new BasicNameValuePair("Qid", vo.getQid()));
	        params.add(new BasicNameValuePair("Hid",vo.getHid()));
	        
	        params.add(new BasicNameValuePair("Pwr",vo.getPwr()));  
	        params.add(new BasicNameValuePair("Qwr",vo.getQwr()));  
	        params.add(new BasicNameValuePair("Hwr", vo.getHwr()));
	        //要传递的参数.  
	        String markUrl = user.getAddress() + "/MarkTJ.aspx?" + URLEncodedUtils.format(params,"UTF-8");
	        System.out.println(vo.getPid() +"="+vo.getPwr());
	        System.out.println(vo.getQid() +"="+vo.getQwr());
	        System.out.println(vo.getHid() +"="+vo.getHwr());
	        HeadParmsVO heads = new HeadParmsVO();
	        heads.setAccept("*/*");
	        heads.setxRequestedWith("XMLHttpRequest");
	        heads.setCookie(cookie);
	        response = instance.sendHttpGet(httpClient, heads, markUrl, proxyInfo);
	        int state = response.getStatusLine().getStatusCode();
	        String resMsg = EntityUtils.toString(response.getEntity(), "UTF-8");
	        System.out.println("resMsg="+resMsg);
	        if (state == HttpStatus.SC_OK) {
	        	//int core = Integer.parseInt(resMsg.substring(0,resMsg.indexOf("|")).split("=")[1]);
	        	print(zyName+"-"+ code +"-考试成功，本次考试成绩为："+resMsg+"分");
	        	resultMap.put("successFlag", "1");
	        	user.setStatus(3);
	        }else{
            	print(zyName+"-"+ code +"-试卷提交失败！------->state="+state);
            }
	        Thread.sleep(5000);
		} catch (Exception e) {
			printError(zyName+"-"+code+"-试卷提交异常--->");
		}finally{
			instance.closeResource(response, httpClient);
			logout(vo,user);
		}
	}
	
	private void setParmsValue(ClassParmsVO vo,User user){
		answerMap = SanLeiConfigUtils.daanMap;
		String[] result1 = (vo.getPid().substring(0, vo.getPid().length()-1)).split(",");
		String[] result2 = (vo.getQid().substring(0, vo.getQid().length()-1)).split(",");
		String[] result3 = (vo.getHid().substring(0, vo.getHid().length()-1)).split(",");
		String Pwr="",Qwr="",Hwr="";
		//设置判断题答案
		for(int i=0;i<result1.length;i++){
			String pid = result1[i];
			String panswer = (String) answerMap.get(pid);
			if(!"Yes".equalsIgnoreCase(panswer)&&!"No".equalsIgnoreCase(panswer)){
				panswer = "Yes";
			}
			if(i==0)
				Pwr = panswer;
			else
				Pwr = Pwr + "," + panswer;
		}
		Pwr = Pwr + ",";
		vo.setPwr(Pwr);
		
		//设置单选题答案
		for(int i=0;i<result2.length;i++){
			String pid = result2[i];
			String panswer = (String) answerMap.get(pid);
			if(!"A".equalsIgnoreCase(panswer)&&!"B".equalsIgnoreCase(panswer)
					&&!"C".equalsIgnoreCase(panswer)&&!"D".equalsIgnoreCase(panswer)){
				panswer = "B";
			}
			if(i==0){
				Qwr = panswer;
			}else{
				Qwr = Qwr + "," + panswer;
			}
				
		}
		Qwr = Qwr + ",";
		vo.setQwr(Qwr);
		//设置多选题答案
		for(int i=0;i<result3.length;i++){
			String pid = result3[i];
			String panswer = (String) answerMap.get(pid);
			if(panswer==null || panswer.trim().length()!=9){
				panswer = "0|B|C|0|E";
			}
			if(i==0)
				Hwr = panswer;
			else
				Hwr = Hwr + "," + panswer;
		}
		Hwr = Hwr + ",";
		vo.setHwr(Hwr);
	}
	
	//安全生产知识培训平台：退出登录
	private void logout(ClassParmsVO vo,User user){
		String userid = vo.getUserid();
		String info = vo.getInfo();
		String sessionId = vo.getSessionId();
		try {
			String uid = userid.substring(userid.indexOf("=")+1,userid.length()-1);
			String path = user.getAddress() + "/Logout.aspx";
			String cookie = sessionId + userid + info +"totaltime=2981;checkUid="+uid+";nowtime=2931";
			HeadParmsVO heads = new HeadParmsVO();
			heads.setAccept("text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			heads.setCookie(cookie);
			response = instance.sendHttpGet(httpClient, heads, path, proxyInfo);
			int state = response.getStatusLine().getStatusCode();
			//System.out.println("logout state="+state);
			if(state == 200 || state == 302){
				//print("退出登录成功!");
			}else{
				//print("退出登录失败!");
			}
		} catch (Exception e) {
			print("退出登录异常--->"+e);
		}finally{
			instance.closeResource(response, httpClient);
		}
	}
	
	
	
	//获得10个1-100随机数，根据数值范围设置ABCD
	public static String getQwr(){
		String qwr = "";
		Set<Integer> set=new HashSet<Integer>();
		while(true){
			int num = (int)(Math.random()*100+1);
			if(set.contains(num))
				continue;
			set.add(num);
			if(num > 75)
				qwr = qwr + "D,";
			if(num >50 && num <= 75)
				qwr = qwr + "C,";
			if(num >25 && num <= 50)
				qwr = qwr + "B,";
			if(num >=1 && num <= 25)
				qwr = qwr + "A,";
			if(set.size()==10)
				break;
		}
		return "A,A,D,C,D,C,C,A,D,D,"+qwr;
	}
	
	private void print(String msg){
		resultMap.put("msg", msg);
		log.info(msg);
	}
	
	private void printError(String errMsg){
		resultMap.put("errMsg", errMsg);
		log.error(errMsg);
	}
}
